package cn.org.wangchangjiu.redis.springcache;

import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;

/**
 * @author wangchangjiu
 * @Classname RedisCacheResolver
 * @Description
 * @Date 2024/8/29 13:44
 */
public class RedisCacheResolver extends RedisCache {

    private final String name;
    private final CacheKeySaver cacheKeySaver;

    protected RedisCacheResolver(String name, RedisCacheWriter cacheWriter, RedisCacheConfiguration cacheConfig, CacheKeySaver cacheKeySaver) {
        super(name, cacheWriter, cacheConfig);
        this.name = name;
        this.cacheKeySaver = cacheKeySaver;
    }

    /**
     *
     * @Title: evict
     * @Description: 重写删除的方法
     * @param  @param key
     * @throws
     *
     */
    @Override
    public void evict(Object key) {
        // 如果key中包含"noCacheable:"关键字的，就不进行缓存处理
        if (key.toString().contains("noCacheable")) {
            return;
        }

        if (key instanceof String) {
            String keyString = key.toString();
            // 后缀删除
            if (keyString.endsWith("*")) {
                CacheKeySaver.KeyResult keyResult = cacheKeySaver.getKey(name);
                if(!CollectionUtils.isEmpty(keyResult.getItems())){
                    keyResult.getItems().stream().forEach(it -> super.evict(it));
                }
                return;
            }
        }
        // 删除指定的key
        super.evict(key);
    }

    @Override
    public void clear(){
        CacheKeySaver.KeyResult keyResult = cacheKeySaver.getKey(name);
        if(!CollectionUtils.isEmpty(keyResult.getItems())){
            keyResult.getItems().stream().forEach(it -> super.evict(it));
        }
    }

    @Override
    public void put(Object key, @Nullable Object value) {
        super.put(key, value);
        this.cacheKeySaver.putKey(name, key.toString());
    }

}
